# -*- coding:utf-8 -*- 
try:
    from BeautifulSoupa import BeautifulSoup
except:
    from BeautifulSoup import BeautifulSoup
import re
import chardet


class findinfo():
    def __init__(self,url):
        self.info={}
        self.url_app_itunes=url
    
    def do_encode(self,tx):
        '''encode the html code to right style'''
        try:
            message_body=tx.encode('utf-8')
        except:
            nb_encode=chardet.detect(tx) 
            nb_code=nb_encode['encoding']
            #logging.info(nb_code)
            message_body=tx.decode(nb_code,'ignore').encode('utf-8')
        return message_body
    
    
    def get_html(self):
        '''get the html code from the web url and anlysis the html code'''
        self.body=urllib2.urlopen(self.url_app_itunes).read()
        self.html=self.do_encode(self.body)
        self.info['name_app']=re.find('<h1>([\s\S]*?)</h1>').[0]
        self.goodhtml=re.findall('''(<div rating-software="100,itunes-games" parental-rating="1" class="lockup product application">[\s\S]*?</div>[\s\S]*?</div>[\S\s]*?</div>[\s\S]*?</div>)''',self.html)[0]

    
    def find_info(self):
        '''find the right data and add it to dict'''
        #self.info={}
        soup1=BeautifulSoup(self.goodhtml)
        self.info['price']=soup1.find('div',{'class':'price'}).string
        self.info['url_app']=soup1.find('a').attrs[0][1]
        self.info['url_img_app']=soup1.find('img').attrs[0][1]
        self.info['language']=soup1.find('li',{'class':'language'}).find('span').nextSibling
        self.info['size']=soup1.findAll('span')[5].nextSibling
        self.info['genre']=soup1.find('li',{'class':'genre'}).find('a').string
        self.info['url_genre']=soup1.find('li',{'class':'genre'}).find('a').attrs[0][1]
        self.info['release-date']=soup1.findAll('li')[2].find('span').nextSibling
        self.info['vesion_app']=soup1.findAll('li')[3].find('span').nextSibling
        self.info['app-requirements']=soup1.find('span',{'class':'app-requirements'}).nextSibling
        self.info['developer']=soup1.findAll('li')[7].find('span').nextSibling
        
    def get_data(self):
        self.get_html()
        self.find_info()
        '''return the dict for Use'''
        return self.info